[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfo } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfo, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { BasicLayout } from '~/components/Layout/BasicLayout';
  21. import { PageView } from '~/components/PageView/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import { RegistrationMode } from '~/interfaces/registration-mode';
  26. import type { RendererConfig } from '~/interfaces/services/renderer';
  27. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  28. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  29. import type { PageModel, PageDocument } from '~/server/models/page';
  30. import type { PageRedirectModel } from '~/server/models/page-redirect';
  31. import { useEditorModeClassName } from '~/services/layout/use-editor-mode-class-name';
  32. import {
  33. useCurrentUser,
  34. useIsForbidden, useIsSharedUser,
  35. useIsEnabledStaleNotification, useIsIdenticalPath,
  36. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  37. useDefaultIndentSize, useIsIndentSizeForced,
  38. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  39. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  40. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  41. useIsAllReplyShown, useIsContainerFluid, useIsNotCreatable,
  42. useIsUploadAllFileAllowed, useIsUploadEnabled,
  43. useElasticsearchMaxBodyLengthToIndex,
  44. useIsLocalAccountRegistrationEnabled,
  45. useIsRomUserAllowedToComment,
  46. useIsAiEnabled,
  47. } from '~/stores-universal/context';
  48. import { useEditingMarkdown } from '~/stores/editor';
  49. import {
  50. useSWRxCurrentPage, useSWRMUTxCurrentPage, useCurrentPageId,
  51. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  52. } from '~/stores/page';
  53. import { useRedirectFrom } from '~/stores/page-redirect';
  54. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  55. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  56. import { useCurrentPageYjsData, useSWRMUTxCurrentPageYjsData } from '~/stores/yjs';
  57. import loggerFactory from '~/utils/logger';
  58. import type { NextPageWithLayout } from './_app.page';
  59. import type { CommonProps } from './utils/commons';
  60. import {
  61. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  62. } from './utils/commons';
  63. declare global {
  64. // eslint-disable-next-line vars-on-top, no-var
  65. var globalEmitter: EventEmitter;
  66. }
  67. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/client/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  68. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  69. const DisplaySwitcher = dynamic(() => import('~/client/components/Page/DisplaySwitcher').then(mod => mod.DisplaySwitcher), { ssr: false });
  70. const PageStatusAlert = dynamic(() => import('~/client/components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  71. const UnsavedAlertDialog = dynamic(() => import('~/client/components/UnsavedAlertDialog'), { ssr: false });
  72. const DescendantsPageListModal = dynamic(
  73. () => import('~/client/components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal),
  74. { ssr: false },
  75. );
  76. const DrawioModal = dynamic(() => import('~/client/components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  77. const HandsontableModal = dynamic(() => import('~/client/components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  78. const TemplateModal = dynamic(() => import('~/client/components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  79. const LinkEditModal = dynamic(() => import('~/client/components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  80. const TagEditModal = dynamic(() => import('~/client/components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  81. const ConflictDiffModal = dynamic(() => import('~/client/components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  82. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  83. const EditablePageEffects = dynamic(() => import('~/client/components/Page/EditablePageEffects').then(mod => mod.EditablePageEffects), { ssr: false });
  84. const logger = loggerFactory('growi:pages:all');
  85. const {
  86. isPermalink: _isPermalink, isCreatablePage,
  87. } = pagePathUtils;
  88. const { removeHeadingSlash } = pathUtils;
  89. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfo>;
  90. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  91. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  92. {
  93. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  94. return v?.data != null
  95. && v?.data.toObject != null
  96. && isIPageInfo(v.meta);
  97. },
  98. serialize: (v) => {
  99. return {
  100. data: superjson.stringify(v.data.toObject()),
  101. meta: superjson.stringify(v.meta),
  102. };
  103. },
  104. deserialize: (v) => {
  105. return {
  106. data: superjson.parse(v.data),
  107. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  108. };
  109. },
  110. },
  111. 'IPageToShowRevisionWithMetaTransformer',
  112. );
  113. // GrowiContextualSubNavigation for NOT shared page
  114. type GrowiContextualSubNavigationProps = {
  115. isLinkSharingDisabled: boolean,
  116. }
  117. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  118. const { isLinkSharingDisabled } = props;
  119. const { data: currentPage } = useSWRxCurrentPage();
  120. return (
  121. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  122. );
  123. };
  124. type Props = CommonProps & {
  125. pageWithMeta: IPageToShowRevisionWithMeta | null,
  126. // pageUser?: any,
  127. redirectFrom?: string;
  128. // shareLinkId?: string;
  129. isLatestRevision?: boolean,
  130. isIdenticalPathPage?: boolean,
  131. isForbidden: boolean,
  132. isNotFound: boolean,
  133. isNotCreatable: boolean,
  134. // isAbleToDeleteCompletely: boolean,
  135. templateTagData?: string[],
  136. templateBodyData?: string,
  137. isLocalAccountRegistrationEnabled: boolean,
  138. isSearchServiceConfigured: boolean,
  139. isSearchServiceReachable: boolean,
  140. isSearchScopeChildrenAsDefault: boolean,
  141. elasticsearchMaxBodyLengthToIndex: number,
  142. isEnabledMarp: boolean,
  143. isRomUserAllowedToComment: boolean,
  144. sidebarConfig: ISidebarConfig,
  145. isSlackConfigured: boolean,
  146. // isMailerSetup: boolean,
  147. isAclEnabled: boolean,
  148. // hasSlackConfig: boolean,
  149. drawioUri: string | null,
  150. // highlightJsStyle: string,
  151. isAllReplyShown: boolean,
  152. isContainerFluid: boolean,
  153. isUploadEnabled: boolean,
  154. isUploadAllFileAllowed: boolean,
  155. isEnabledStaleNotification: boolean,
  156. isEnabledAttachTitleHeader: boolean,
  157. // isEnabledLinebreaks: boolean,
  158. // isEnabledLinebreaksInComments: boolean,
  159. adminPreferredIndentSize: number,
  160. isIndentSizeForced: boolean,
  161. disableLinkSharing: boolean,
  162. skipSSR: boolean,
  163. ssrMaxRevisionBodyLength: number,
  164. yjsData: CurrentPageYjsData,
  165. rendererConfig: RendererConfig,
  166. aiEnabled: boolean,
  167. };
  168. const Page: NextPageWithLayout<Props> = (props: Props) => {
  169. // register global EventEmitter
  170. if (isClient() && window.globalEmitter == null) {
  171. window.globalEmitter = new EventEmitter();
  172. }
  173. const router = useRouter();
  174. useCurrentUser(props.currentUser ?? null);
  175. // commons
  176. useCsrfToken(props.csrfToken);
  177. useGrowiCloudUri(props.growiCloudUri);
  178. // page
  179. useIsContainerFluid(props.isContainerFluid);
  180. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  181. useIsForbidden(props.isForbidden);
  182. useIsNotCreatable(props.isNotCreatable);
  183. useRedirectFrom(props.redirectFrom ?? null);
  184. useIsSharedUser(false); // this page cann't be routed for '/share'
  185. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  186. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  187. useIsSearchPage(false);
  188. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  189. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  190. useIsSearchServiceReachable(props.isSearchServiceReachable);
  191. useElasticsearchMaxBodyLengthToIndex(props.elasticsearchMaxBodyLengthToIndex);
  192. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  193. useIsSlackConfigured(props.isSlackConfigured);
  194. // useIsMailerSetup(props.isMailerSetup);
  195. useIsAclEnabled(props.isAclEnabled);
  196. // useHasSlackConfig(props.hasSlackConfig);
  197. useDefaultIndentSize(props.adminPreferredIndentSize);
  198. useIsIndentSizeForced(props.isIndentSizeForced);
  199. useDisableLinkSharing(props.disableLinkSharing);
  200. useRendererConfig(props.rendererConfig);
  201. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  202. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  203. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  204. useIsAllReplyShown(props.isAllReplyShown);
  205. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  206. useIsUploadEnabled(props.isUploadEnabled);
  207. useIsLocalAccountRegistrationEnabled(props.isLocalAccountRegistrationEnabled);
  208. useIsRomUserAllowedToComment(props.isRomUserAllowedToComment);
  209. useIsAiEnabled(props.aiEnabled);
  210. const { pageWithMeta } = props;
  211. const pageId = pageWithMeta?.data._id;
  212. const revisionId = pageWithMeta?.data.revision?._id;
  213. const revisionBody = pageWithMeta?.data.revision?.body;
  214. useCurrentPathname(props.currentPathname);
  215. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  216. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  217. const { trigger: mutateCurrentPageYjsDataFromApi } = useSWRMUTxCurrentPageYjsData();
  218. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  219. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  220. const { mutate: mutateIsNotFound } = useIsNotFound();
  221. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  222. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  223. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  224. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  225. const { mutate: mutateCurrentPageYjsData } = useCurrentPageYjsData();
  226. useSetupGlobalSocket();
  227. useSetupGlobalSocketForPage(pageId);
  228. // Store initial data (When revisionBody is not SSR)
  229. useEffect(() => {
  230. if (!props.skipSSR) {
  231. return;
  232. }
  233. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  234. const mutatePageData = async() => {
  235. const pageData = await mutateCurrentPage();
  236. mutateEditingMarkdown(pageData?.revision?.body);
  237. };
  238. // If skipSSR is true, use the API to retrieve page data.
  239. // Because pageWIthMeta does not contain revision.body
  240. mutatePageData();
  241. }
  242. }, [
  243. revisionId, currentPageId, mutateCurrentPage,
  244. mutateCurrentPageYjsDataFromApi, mutateEditingMarkdown, props.isNotFound, props.skipSSR,
  245. ]);
  246. // Load current yjs data
  247. useEffect(() => {
  248. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  249. mutateCurrentPageYjsDataFromApi();
  250. }
  251. }, [currentPageId, mutateCurrentPageYjsDataFromApi, props.isNotFound, revisionId]);
  252. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  253. useEffect(() => {
  254. const decodedURI = decodeURI(window.location.pathname);
  255. if (isClient() && decodedURI !== props.currentPathname) {
  256. const { search, hash } = window.location;
  257. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  258. }
  259. }, [props.currentPathname, router]);
  260. // initialize mutateEditingMarkdown only once per page
  261. // need to include useCurrentPathname not useCurrentPagePath
  262. useEffect(() => {
  263. if (props.currentPathname != null) {
  264. mutateEditingMarkdown(revisionBody);
  265. }
  266. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  267. useEffect(() => {
  268. mutateRemoteRevisionId(revisionId);
  269. }, [mutateRemoteRevisionId, revisionId]);
  270. useEffect(() => {
  271. mutateCurrentPageId(pageId ?? null);
  272. }, [mutateCurrentPageId, pageId]);
  273. useEffect(() => {
  274. mutateIsNotFound(props.isNotFound);
  275. }, [mutateIsNotFound, props.isNotFound]);
  276. useEffect(() => {
  277. mutateIsLatestRevision(props.isLatestRevision);
  278. }, [mutateIsLatestRevision, props.isLatestRevision]);
  279. useEffect(() => {
  280. mutateTemplateTagData(props.templateTagData);
  281. }, [props.templateTagData, mutateTemplateTagData]);
  282. useEffect(() => {
  283. mutateTemplateBodyData(props.templateBodyData);
  284. }, [props.templateBodyData, mutateTemplateBodyData]);
  285. useEffect(() => {
  286. mutateCurrentPageYjsData(props.yjsData);
  287. }, [mutateCurrentPageYjsData, props.yjsData]);
  288. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  289. // So preferentially take page data from useSWRxCurrentPage
  290. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  291. const title = generateCustomTitleForPage(props, pagePath);
  292. return (
  293. <>
  294. <Head>
  295. <title>{title}</title>
  296. </Head>
  297. <div className="dynamic-layout-root justify-content-between">
  298. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  299. <PageView
  300. className="d-edit-none"
  301. pagePath={pagePath}
  302. initialPage={pageWithMeta?.data}
  303. rendererConfig={props.rendererConfig}
  304. />
  305. <EditablePageEffects />
  306. <DisplaySwitcher />
  307. <PageStatusAlert />
  308. </div>
  309. </>
  310. );
  311. };
  312. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  313. const editorModeClassName = useEditorModeClassName();
  314. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  315. };
  316. type LayoutProps = Props & {
  317. children?: ReactNode
  318. }
  319. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  320. // init sidebar config with UserUISettings and sidebarConfig
  321. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  322. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  323. };
  324. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  325. return (
  326. <>
  327. <GrowiPluginsActivator />
  328. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  329. <Layout {...page.props}>
  330. {page}
  331. </Layout>
  332. <UnsavedAlertDialog />
  333. <DescendantsPageListModal />
  334. <DrawioModal />
  335. <HandsontableModal />
  336. <QuestionnaireModalManager />
  337. <TemplateModal />
  338. <LinkEditModal />
  339. <TagEditModal />
  340. <ConflictDiffModal />
  341. </>
  342. );
  343. };
  344. function getPageIdFromPathname(currentPathname: string): string | null {
  345. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  346. }
  347. class MultiplePagesHitsError extends ExtensibleCustomError {
  348. pagePath: string;
  349. constructor(pagePath: string) {
  350. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  351. this.pagePath = pagePath;
  352. }
  353. }
  354. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  355. const { model: mongooseModel } = await import('mongoose');
  356. const req: CrowiRequest = context.req as CrowiRequest;
  357. const { crowi } = req;
  358. const { revisionId } = req.query;
  359. const Page = crowi.model('Page') as PageModel;
  360. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  361. const { pageService, configManager } = crowi;
  362. let currentPathname = props.currentPathname;
  363. const pageId = getPageIdFromPathname(currentPathname);
  364. const isPermalink = _isPermalink(currentPathname);
  365. const { user } = req;
  366. if (!isPermalink) {
  367. // check redirects
  368. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  369. if (chains != null) {
  370. // overwrite currentPathname
  371. currentPathname = chains.end.toPath;
  372. props.currentPathname = currentPathname;
  373. // set redirectFrom
  374. props.redirectFrom = chains.start.fromPath;
  375. }
  376. // check whether the specified page path hits to multiple pages
  377. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  378. if (count > 1) {
  379. throw new MultiplePagesHitsError(currentPathname);
  380. }
  381. }
  382. const pageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  383. const { data: page, meta } = pageWithMeta ?? {};
  384. // add user to seen users
  385. if (page != null && user != null) {
  386. await page.seen(user);
  387. }
  388. props.pageWithMeta = null;
  389. // populate & check if the revision is latest
  390. if (page != null) {
  391. page.initLatestRevisionField(revisionId);
  392. props.isLatestRevision = page.isLatestRevision();
  393. const ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  394. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  395. const populatedPage = await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  396. props.pageWithMeta = {
  397. data: populatedPage,
  398. meta,
  399. };
  400. }
  401. }
  402. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  403. const req: CrowiRequest = context.req as CrowiRequest;
  404. const { crowi } = req;
  405. const Page = crowi.model('Page') as PageModel;
  406. const { currentPathname } = props;
  407. const pageId = getPageIdFromPathname(currentPathname);
  408. const isPermalink = _isPermalink(currentPathname);
  409. const page = props.pageWithMeta?.data;
  410. if (props.isIdenticalPathPage) {
  411. props.isNotCreatable = true;
  412. }
  413. else if (page == null) {
  414. props.isNotFound = true;
  415. props.isNotCreatable = !isCreatablePage(currentPathname);
  416. // check the page is forbidden or just does not exist.
  417. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  418. props.isForbidden = count > 0;
  419. }
  420. else {
  421. props.isNotFound = page.isEmpty;
  422. props.isNotCreatable = false;
  423. props.isForbidden = false;
  424. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  425. if (isPermalink && page.isEmpty) {
  426. props.currentPathname = page.path;
  427. }
  428. // /path/to/page ==> /62a88db47fed8b2d94f30000
  429. if (!isPermalink && !page.isEmpty) {
  430. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  431. if (!isToppage) {
  432. props.currentPathname = `/${page._id}`;
  433. }
  434. }
  435. if (!props.skipSSR) {
  436. props.yjsData = await crowi.pageService.getYjsData(page._id.toString());
  437. }
  438. }
  439. }
  440. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  441. // const req: CrowiRequest = context.req as CrowiRequest;
  442. // const { crowi } = req;
  443. // const UserModel = crowi.model('User');
  444. // if (isUserPage(props.currentPagePath)) {
  445. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  446. // if (user != null) {
  447. // props.pageUser = JSON.stringify(user.toObject());
  448. // }
  449. // }
  450. // }
  451. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  452. const req: CrowiRequest = context.req as CrowiRequest;
  453. const { crowi } = req;
  454. const {
  455. configManager, searchService, aclService, fileUploadService,
  456. slackIntegrationService, passportService,
  457. } = crowi;
  458. props.aiEnabled = configManager.getConfig('app:aiEnabled');
  459. props.isSearchServiceConfigured = searchService.isConfigured;
  460. props.isSearchServiceReachable = searchService.isReachable;
  461. props.isSearchScopeChildrenAsDefault = configManager.getConfig('customize:isSearchScopeChildrenAsDefault');
  462. props.elasticsearchMaxBodyLengthToIndex = configManager.getConfig('app:elasticsearchMaxBodyLengthToIndex');
  463. props.isRomUserAllowedToComment = configManager.getConfig('security:isRomUserAllowedToComment');
  464. props.isSlackConfigured = slackIntegrationService.isSlackConfigured;
  465. // props.isMailerSetup = mailService.isMailerSetup;
  466. props.isAclEnabled = aclService.isAclEnabled();
  467. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  468. props.drawioUri = configManager.getConfig('app:drawioUri');
  469. // props.highlightJsStyle = configManager.getConfig('customize:highlightJsStyle');
  470. props.isAllReplyShown = configManager.getConfig('customize:isAllReplyShown');
  471. props.isContainerFluid = configManager.getConfig('customize:isContainerFluid');
  472. props.isEnabledStaleNotification = configManager.getConfig('customize:isEnabledStaleNotification');
  473. props.disableLinkSharing = configManager.getConfig('security:disableLinkSharing');
  474. props.isUploadAllFileAllowed = fileUploadService.getFileUploadEnabled();
  475. props.isUploadEnabled = fileUploadService.getIsUploadable();
  476. props.isLocalAccountRegistrationEnabled = passportService.isLocalStrategySetup
  477. && configManager.getConfig('security:registrationMode') !== RegistrationMode.CLOSED;
  478. props.adminPreferredIndentSize = configManager.getConfig('markdown:adminPreferredIndentSize');
  479. props.isIndentSizeForced = configManager.getConfig('markdown:isIndentSizeForced');
  480. props.isEnabledAttachTitleHeader = configManager.getConfig('customize:isEnabledAttachTitleHeader');
  481. props.sidebarConfig = {
  482. isSidebarCollapsedMode: configManager.getConfig('customize:isSidebarCollapsedMode'),
  483. isSidebarClosedAtDockMode: configManager.getConfig('customize:isSidebarClosedAtDockMode'),
  484. };
  485. props.rendererConfig = {
  486. isEnabledLinebreaks: configManager.getConfig('markdown:isEnabledLinebreaks'),
  487. isEnabledLinebreaksInComments: configManager.getConfig('markdown:isEnabledLinebreaksInComments'),
  488. isEnabledMarp: configManager.getConfig('customize:isEnabledMarp'),
  489. adminPreferredIndentSize: configManager.getConfig('markdown:adminPreferredIndentSize'),
  490. isIndentSizeForced: configManager.getConfig('markdown:isIndentSizeForced'),
  491. drawioUri: configManager.getConfig('app:drawioUri'),
  492. plantumlUri: configManager.getConfig('app:plantumlUri'),
  493. // XSS Options
  494. isEnabledXssPrevention: configManager.getConfig('markdown:rehypeSanitize:isEnabledPrevention'),
  495. sanitizeType: configManager.getConfig('markdown:rehypeSanitize:option'),
  496. customTagWhitelist: configManager.getConfig('markdown:rehypeSanitize:tagNames'),
  497. customAttrWhitelist: configManager.getConfig('markdown:rehypeSanitize:attributes') != null
  498. ? JSON.parse(configManager.getConfig('markdown:rehypeSanitize:attributes'))
  499. : undefined,
  500. highlightJsStyleBorder: configManager.getConfig('customize:highlightJsStyleBorder'),
  501. };
  502. props.ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  503. }
  504. /**
  505. * for Server Side Translations
  506. * @param context
  507. * @param props
  508. * @param namespacesRequired
  509. */
  510. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  511. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  512. props._nextI18Next = nextI18NextConfig._nextI18Next;
  513. }
  514. const getAction = (props: Props): SupportedActionType => {
  515. if (props.isNotCreatable) {
  516. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  517. }
  518. if (props.isForbidden) {
  519. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  520. }
  521. if (props.isNotFound) {
  522. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  523. }
  524. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  525. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  526. }
  527. return SupportedAction.ACTION_PAGE_VIEW;
  528. };
  529. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  530. const req = context.req as CrowiRequest;
  531. const { user } = req;
  532. const result = await getServerSideCommonProps(context);
  533. // check for presence
  534. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  535. if (!('props' in result)) {
  536. throw new Error('invalid getSSP result');
  537. }
  538. const props: Props = result.props as Props;
  539. if (props.redirectDestination != null) {
  540. return {
  541. redirect: {
  542. permanent: false,
  543. destination: props.redirectDestination,
  544. },
  545. };
  546. }
  547. if (user != null) {
  548. props.currentUser = user.toObject();
  549. }
  550. try {
  551. await injectPageData(context, props);
  552. }
  553. catch (err) {
  554. if (err instanceof MultiplePagesHitsError) {
  555. props.isIdenticalPathPage = true;
  556. }
  557. else {
  558. throw err;
  559. }
  560. }
  561. await injectRoutingInformation(context, props);
  562. injectServerConfigurations(context, props);
  563. await injectNextI18NextConfigurations(context, props, ['translation']);
  564. addActivity(context, getAction(props));
  565. return {
  566. props,
  567. };
  568. };
  569. export default Page;